package com.xinqi.modules.chat.chat.message.service.impl;

import com.xinqi.common.base.enums.YesNoNumberEnum;
import com.xinqi.common.core.constant.ChatConstants;
import com.xinqi.modules.chat.chat.friend.domain.ChatFriendEntity;
import com.xinqi.modules.chat.chat.friend.manager.ChatFriendManager;
import com.xinqi.modules.chat.chat.message.convert.ChatMessageCountConvert;
import com.xinqi.modules.chat.chat.message.domain.ChatMessageCountEntity;
import com.xinqi.modules.chat.chat.message.dto.req.ChatMessageCountDeleteDTO;
import com.xinqi.modules.chat.chat.message.manager.ChatMessageCountManager;
import com.xinqi.modules.chat.chat.message.service.ChatMessageCountService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;


/**
 * 陌生人聊天限制服务层实现
 *
 * @author: yyzhen
 * @date: 2023/06/02
 */
@Service("chatMessageCountService")
@RequiredArgsConstructor
public class ChatMessageCountServiceImpl implements ChatMessageCountService {
    private final ChatMessageCountConvert chatMessageCountConvert;
    private final ChatMessageCountManager chatMessageCountManager;

    private final ChatFriendManager chatFriendManager;

    /**
     * 校验陌生人聊天限制数据
     *
     * @param receiveId
     * @param operationUserId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean checkCount(Long receiveId, Long operationUserId) {
        ChatFriendEntity friend = chatFriendManager.friedByUserIdFriendId(operationUserId, receiveId);
        if (Objects.nonNull(friend) && Objects.equals(YesNoNumberEnum.YES.getCode(), friend.getIsFriend())) {
            //是好友（不区分黑名单，黑名单无法聊天）、无限制
             return Boolean.TRUE;
        }

        ChatMessageCountEntity entity = chatMessageCountManager.initCount(receiveId, operationUserId);
        //陌生人可以发送3条消息
        if (Objects.isNull(entity)) {
            entity = new ChatMessageCountEntity();
            entity.setSendId(operationUserId);
            entity.setReceiveId(receiveId);
            entity.setUsedCount(1);
            this.chatMessageCountManager.save(entity);
             return Boolean.TRUE;
        } else if (entity.getUsedCount() < ChatConstants.CHAT_MESSAGE_COUNT_LIMIT) {
            entity.setUsedCount(entity.getUsedCount() + 1);
            this.chatMessageCountManager.updateById(entity);
             return Boolean.TRUE;
        } else {
            return false;
        }
    }

    /**
     * 删除 陌生人聊天限制数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(ChatMessageCountDeleteDTO dto) {
        return this.chatMessageCountManager.deleteById(dto.getReceiveId(), dto.getSendId());
    }

}
